import fse from "fs-extra";
import { fdir } from "fdir";
import path from "path";
import fs from "node:fs";

const from = "./dist";

function renameFileContent(filePath, from, to) {
  const content = fs.readFileSync(filePath).toString();
  fs.writeFileSync(filePath, content.replace(from, to));
}

function renameFile(filePath) {
  const { dir, name, ext } = path.parse(filePath);
  let newName = name.replace(/\.[^.]{8}/, "");

  const newPath = path.format({
    dir,
    name: newName,
    ext,
  });
  fse.moveSync(filePath, newPath);
}

function single(ext) {
  const filePath = new fdir()
    .glob([`**/*${ext}`])
    .withFullPaths()
    .crawl(from)
    .sync()[0];

  const originalFileName = path.basename(filePath);
  const mapPath = filePath + ".map";

  renameFileContent(filePath, originalFileName, `index${ext}`);
  renameFileContent(mapPath, originalFileName, `index${ext}`);
  renameFile(filePath);
  renameFile(mapPath);

  console.log(`重命名 ${ext}`);
}

single(".js");
single(".css");
